package woa.stack;

import java.util.*;

/**
 * 每日温度问题
 * 请根据每日 气温 列表 temperatures ，请计算在每一天需要等几天才会有更高的温度。如果气温在这之后都不会升高，请在该位置
 * 用 0 来代替。
 *
 * 输入: temperatures = [73,74,75,71,69,72,76,73]
 * 输出: [1,1,4,2,1,1,0,0]
 *
 * @author wangpeng
 * @date 2021/11/28
 */
public class DailyTemperaturesProblem {

    static class LinkedNode {
        int temperature;
        int index;

        public LinkedNode(int temperature, int index) {
            this.temperature = temperature;
            this.index = index;
        }
    }

    /**
     * 暴力法，超出时间限制
     *
     * @param temperatures
     * @return
     */
    public static int[] dailyTemperatures(int[] temperatures) {
        int[] rs = new int[temperatures.length];
        List<LinkedNode> list = new LinkedList<>();
        for (int i = 0; i < temperatures.length; i++) {
            int t = temperatures[i];
            Iterator<LinkedNode> it = list.iterator();
            while (it.hasNext()) {
                LinkedNode node = it.next();
                if (node.temperature < t) {
                    rs[node.index] = i - node.index;
                    it.remove();
                } else {
                    break;
                }
            }
            list.add(new LinkedNode(t, i));
        }
        return rs;
    }

    /**
     * 使用栈保存下标
     *
     * @param temperatures
     * @return
     */
    public static int[] dailyTemperatures1(int[] temperatures) {
        int[] rs = new int[temperatures.length];
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < temperatures.length; i++) {
            int t = temperatures[i];
            while (!stack.isEmpty()) {
                int p = stack.peek();
                if (temperatures[p] < t) {
                    rs[p] = i - p;
                    stack.pop();
                } else {
                    break;
                }
            }
            stack.add(i);
        }
        return rs;
    }

    /**
     * 从后往前，根据已经处理的数据推导未处理的数据
     *
     * @param temperatures
     * @return
     */
    public static int[] dailyTemperatures2(int[] temperatures) {
        int len = temperatures.length;
        int[] rs = new int[len];
        for (int i = len - 1; i >= 0; i--) {
            int t = temperatures[i];
            int j = i + 1;
            while (j < len) {
                if (t < temperatures[j]) {
                    rs[i] = j - i;
                    break;
                } else if (rs[j] > 0) {
                    j = j + rs[j];
                } else {
                    break;
                }
            }
        }
        return rs;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(dailyTemperatures2(new int[]{73, 76, 75, 71, 69, 72, 77, 78})));
    }
}
